<?php

require_once CORE_DIRECTORY.OS_PATH_SEPARATOR.'basePlugin.php';

/*
 * BaseThumbnail is the parent class of thumbnails plugins
 * It handles one file and try to make its thumbnail using cache if possible
 */
class BaseThumbnail extends BasePlugin
{
	protected $file;

	// Return the URI of the generated thumbnail
	public function getThumbnail()
	{
		return $this->getFromCache();
	}
	
	// Return the URI of the cached thumbnail if available
	private function getFromCache()
	{
		$hit = glob(THUMBNAIL_DIRECTORY.OS_PATH_SEPARATOR.$this->file->getId().'.*');
		if(!empty($hit))
		{
			return debug($hit[0], 'Hit from thumbnail cache', JGLIB_DEBUG_INFO);
		}
		return false;
	}
	
	// Save to cache dispatcher
	protected function saveToCache($e)
	{
		if(is_resource($e))
		{
			return $this->saveResouceToCache($e);
		}
		else
		{
			return $this->saveImageToCache($e);
		}
	}
	
	// Save the image to the cache (resource image link)
	private function saveResouceToCache($thumbnail)
	{
		$path = THUMBNAIL_DIRECTORY.OS_PATH_SEPARATOR.$this->file->getId().'.jpg';
		if(!@imagejpeg($thumbnail, $path, THUMBNAIL_QUALITY))
		{
			debug('Error when trying to save the thumbnail, is the right are ok, is the directory exist ?'.'%v', JGLIB_DEBUG_ERRR);
			return false;
		}
		return $path;
	}
	
	// Save the image to the cache (image uri)
	private function saveImageToCache($uri)
	{
		$ext = strtolower(substr(strrchr(basename($uri), "."), 1));
		if(!in_array($ext, array('jpg','gif','png')))
		{
			throw new Exception('The URI is not a valid JPG/GIF/PNG image');
		}
		
		$path = THUMBNAIL_DIRECTORY.OS_PATH_SEPARATOR.$this->file->getId().'.'.$ext;
		copy($uri, $path);
		return $path;
	}
	
	// Get a new instance of this plugin with the file to handle
	public function __construct($file)
	{
		if(is_object($file))
		{
			$this->file = $file;
		}
		else
		{
			throw new Exception('$file isn\'t a valid File Object');
		}
	}
	
	// Get the plugin priority as for thumbnail plugin only one is call per file
	// The one with the higher priority is two or more can handle the file (same mime type or extension)
	// Arbitrary value
	public static function getPriority()
	{
		return 0;
	}
}
